using UnityEngine;
using System;
using System.Xml;
using System.IO;

public class NetworkScript : MonoBehaviour
{
	public GameObject cubePrefab;
	private int port;
	private string gameTypeName;
	DataScript data;
	void Awake()
	{
		DontDestroyOnLoad(this.gameObject);
	}
	
	void Start()
	{


		XmlDocument xmlDoc = XmlTools.loadFromPath(Application.dataPath + "/config.xml");
		//XmlNodeList configData =  xmlDoc.SelectNodes("//Config");
		XmlNode configNode = xmlDoc.SelectSingleNode("//serverIP");
		
		MasterServer.ipAddress = configNode.InnerText;
		Network.natFacilitatorIP = configNode.InnerText;
		
		configNode = xmlDoc.SelectSingleNode("//serverPort");
		MasterServer.port = int.Parse(configNode.InnerText);
		configNode = xmlDoc.SelectSingleNode("//NATPort");
		Network.natFacilitatorPort = int.Parse(configNode.InnerText);
		configNode = xmlDoc.SelectSingleNode("//gamePort");
		port = int.Parse(configNode.InnerText);
		configNode = xmlDoc.SelectSingleNode("//gameTypeName");
		gameTypeName = configNode.InnerText;
		
		data = GameObject.FindGameObjectWithTag("DataManager").GetComponent<DataScript>();
		//MasterServer.RequestHostList(gameTypeName);
		//MasterServer.PollHostList();
	}
	
	void Update()
	{
		///if(Input.GetKeyDown(KeyCode.I))
		//{
			//Debug.Log("AW");
		//	Network.Connect("localhost",25003);
		//}
		//if(Input.GetKeyDown(KeyCode.S))
		//{
			//XMLReaderWriter.MapInfoXML mixml= new XMLReaderWriter.MapInfoXML("YourMapName.xml");
			//Debug.Log(mixml.extractString());
			//networkView.RPC("RPC_sendMap",RPCMode.Others,"YourMapName.xml",System.Text.Encoding.ASCII.GetBytes(mixml.extractString()));
		//}
	}
	
	//public functions
	public void startServer(string comment)
	{
		int connections = 1;
		Network.InitializeServer(connections, port, !Network.HavePublicAddress());
		MasterServer.RegisterHost(gameTypeName,"MIRACLE_BETA",comment);
		
		
		//XMLReaderWriter.MapInfoXML mixml= new XMLReaderWriter.MapInfoXML("YourMapName.xml");
		//Debug.Log(mixml.extractString());
		//networkView.RPC("RPC_sendMap",RPCMode.Others,"YourMapName.xml",mixml.extractString());
	}
	
	[RPC]
	void RPC_sendMap(string mapName, byte[] lvlData)
	{
		string myString = System.Text.Encoding.ASCII.GetString(lvlData);
		//Debug.Log(myString.Length);
		
		XMLReaderWriter.MapInfoXML mixml = new XMLReaderWriter.MapInfoXML(mapName);
		mixml.saveMap(myString);
	}
	
	public void loadLevel(int level)
	{
		networkView.RPC("RPC_loadLevel", RPCMode.All,level);
	}
	
	[RPC]
	void RPC_loadLevel(int level)
	{
		Application.LoadLevel("GameScene(Proto)");
	}
	
	public void refreshList()
	{
		//WARNING NEED TO REENABLE
		MasterServer.RequestHostList(gameTypeName);
	}
	
	public void joinServer(HostData hostData)
	{
		Network.Connect(hostData);
	}
	
	//Events
	void OnPlayerConnected(NetworkPlayer player)
	{
		
		XMLReaderWriter.MapInfoXML mixml= new XMLReaderWriter.MapInfoXML(data.loadedLevel + ".xml");
		Debug.Log(data.loadedLevel);
		networkView.RPC("RPC_sendMap",RPCMode.Others,data.loadedLevel + ".xml",System.Text.Encoding.ASCII.GetBytes(mixml.extractString()));
		//numConnections++;
		//Debug.Log(numConnections.ToString() + " connected. I am a server and " + player.ipAddress + " connected to me.");
	}
	
	void OnServerInitialized()
	{
		
		Debug.Log("I am a server that was just started.");
		//Network.Instantiate(cubePrefab, Vector3.zero, Quaternion.identity, 0);
	}
	
	void OnMasterServerEvent(MasterServerEvent mse)
	{
		if(mse == MasterServerEvent.RegistrationSucceeded)
		{
			Debug.Log("MSE REG Succeed");
		}
	}
	
	void OnConnectedToServer()
	{
		Debug.Log("I am a client that just connected.");
		//GameObject cube = (GameObject) Network.Instantiate(cubePrefab, Vector3.zero, Quaternion.identity, 0);
		//cube.GetComponent<ControlCube>().name = name;
	}
	
	void OnPlayerDisconnected(NetworkPlayer player)
	{
		//numConnections--;
		//Debug.Log(numConnections.ToString() + " connected. I am a server and " + player.ipAddress + " just disconnected");
	}
	
	void OnDisconnectedFromServer()
	{
		Debug.Log("I am a client that disconnected from the server");
		//Show Disconnected Screen;
	}
	
	void OnFailedToConnect(NetworkConnectionError error)
	{
		Debug.Log("GMPROG2 error - " + error);
	}
}
